<?php
// +----------------------------------------------------------------------
// | ZengCMS [ 火火 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://zengcms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 火火 <zengcms@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 配置控制器
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\Db;
use think\facade\View;
use app\common\annotation\NodeAnotation;
use app\common\annotation\ControllerAnnotation;
/**
 * @ControllerAnnotation(title="配置管理")
 * Class Config
 * @package app\admin\controller
 */
class Config extends Base 
{
	// 初始化
    protected function initialize()
    {
        parent::initialize();
        $filepath = APP_PATH . DIRECTORY_SEPARATOR . 'admin' . DIRECTORY_SEPARATOR . "view" . DIRECTORY_SEPARATOR . 'custom' . DIRECTORY_SEPARATOR;
        $custom   = str_replace($filepath . DIRECTORY_SEPARATOR, '', glob($filepath . DIRECTORY_SEPARATOR . 'custom*'));
        View::assign('custom', $custom);
    }
	/**
     * @NodeAnotation(title="列表")
     */
	public function index() 
	{
		$map = array();
		$query = array();
		$typeid = trim(input('typeid'));
		$type = trim(input('type'));
		$status = trim(input('status'));
		$title = trim(input('title'));
		if ($typeid !== '' && is_numeric($typeid)) {
			$map[] = ['typeid', '=', $typeid];
			$query['typeid'] = $typeid;
		}
		if($type){
			$map[] = ['type', '=', $type];
			$query['type'] = $type;
		}
		if ($status !== '' && ($status == 0 || $status == 1)) {
			$map[] = ['c.status', '=', $status];
			$query['status'] = $status;
		}
		if ($title) {
			$map[] = ['name|title', 'like', "%$title%"];
			$query['title'] = $title;
		}
		$list = Db::name('config')->alias('c')->field('c.*,ct.title as ct_title')
		->leftJoin('config_type ct', 'c.typeid=ct.id')
		->where($map)
		->order(['c.sort' => 'desc', 'c.id' => 'asc'])
		->paginate(['list_rows'=> sys_config('WEB_ONE_PAGE_NUMBER'),'var_page' => 'page','query' => $query])
		->each(function ($item, $key) {
			int_to_string($item, array('status' => array('0' => '隐藏', '1' => '显示')));
			int_to_string($item, array('iscore' => array('0' => '否', '1' => '是')));
			return $item;
		});
		// 所有配置类型信息
		$configTypeRes = Db::name('config_type')->order('sort desc,id desc')->select()->toArray();
		View::assign([
			'meta_title' => '配置列表',
			'list' => $list,
			'status' => $status,
			'configTypeRes' => $configTypeRes,
			'typeid' => $typeid,
			'type' => $type,
		]);
		// 记录当前列表页的cookie
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		return view();
	}
	/**
     * @NodeAnotation(title="新增")
     */
	public function add() 
	{
		if (request()->isAjax()) {
			$data = input('post.');
			$validate = validate('Config');
			if (!$validate->scene('add')->check($data)) {
				$this->error($validate->getError());
			}
			if(strstr($data['name'],'_text') == '_text'){
				$this->error('英文名称尾部不能携带_text');
			}
			// 可选值处理
			$data['extra'] =  str_replace('，', ',', $data['extra']);//把中文逗号改为英文逗号
			$data['extra'] =  str_replace('：', ':', $data['extra']);//把中文冒号改为英文冒号
			// 默认值处理
			$data['value'] =  str_replace('，', ',', $data['value']);//把中文逗号改为英文逗号
			$data['value'] =  str_replace('：', ':', $data['value']);//把中文冒号改为英文冒号
			$data['create_time'] = time();
			$data['update_time'] = time();
			$data['setting'] = isset($data['setting'])?serialize($data['setting']):'';
			$id = Db::name('config')->strict(false)->insertGetId($data);
			if (!$id) {
				$this->error('新增出错！');
			}
			action_log($id, 'config', 1);
			$this->success('新增成功！');
		} else {
			$info = null;
			$typeid = trim(input('typeid'));//配置类型id
			$configTypeRes = Db::name('config_type')->select()->toArray();//所有配置类型信息
			View::assign([
				'meta_title' => '新增配置',
				'info' => $info,
				'configTypeRes' => $configTypeRes,
				'typeid' => $typeid,
			]);
			return view('edit');
		}
	}
	/**
     * @NodeAnotation(title="编辑")
     */
	public function edit($id = null) 
	{
		if (empty($id)) {
			$this->error('参数错误！');
		}
		$info = Db::name('config')->find($id);
		if (request()->isAjax()) {
			$data = input('post.');
			$validate = validate('Config');
			if (!$validate->scene('edit')->check($data)) {
				$this->error($validate->getError());
			}
			if(strstr($data['name'],'_text') == '_text'){
				$this->error('英文名称尾部不能携带_text');
			}
			// 可选值处理
			$data['extra'] =  str_replace('，', ',', $data['extra']);//把中文逗号改为英文逗号
			$data['extra'] =  str_replace('：', ':', $data['extra']);//把中文冒号改为英文冒号
			// 默认值处理
			$data['value'] =  str_replace('，', ',', $data['value']);//把中文逗号改为英文逗号
			$data['value'] =  str_replace('：', ':', $data['value']);//把中文冒号改为英文冒号
			$data['id'] = intval($data['id']);
			if ($data['id'] == 0) {
				$this->error('非法操作！');
			}
			$data['update_time'] = time();
			action_log($data['id'], 'config', 2);//记录修改前行为
			$data['setting'] = isset($data['setting'])?serialize($data['setting']):'';
			$res = Db::name('config')->strict(false)->where('id',$data['id'])->update($data);
			if (!$res) {
				$this->error('更新出错！');
			}
			action_log($data['id'], 'config', 2);//记录修改后行为
			if ($info['sort'] == $data['sort']) {
				// 判断是否修改排序值如果修改就跳转到列表页，没有修改就跳转当前页
				$this->success('更新成功！',cookie('__forward__'));
			} else {
				$this->success('更新成功！');
			}
		} else {
			if (!$info) {
				$this->error('信息错误！');
			}
			$info['setting'] = unserialize($info['setting']);
			// 所有配置类型信息
			$configTypeRes = Db::name('config_type')->select()->toArray();
			View::assign([
				'meta_title' => '编辑配置',
				'info' => $info,
				'configTypeRes' => $configTypeRes,
			]);
			return view();
		}
	}
	/**
     * @NodeAnotation(title="删除")
     */
	public function del($ids = NULL) 
	{
		$ids = !empty($ids) ? $ids : input('ids', 0);
		if (empty($ids)) {
			$this->error('参数不能为空！');
		}
		if (!is_array($ids)) {
			$ids = array(intval($ids));
		}
		$map = [
			['iscore', '=', 1],
			['id', 'in', $ids],
		];
		if (Db::name('config')->field('value')->where($map)->count()) {
			$this->error('核心配置不能删除！');
		}
		foreach ($ids as $k => $v) {
			action_log($v, 'config', 3);
			$res = Db::name('config')->delete($v);
			if (!$res) {
				$this->error('删除失败！');
			}
		}
		$this->success('删除成功！');
	}
	/**
	 * @NodeAnotation(title="状态")
	 */
	public function setStatus($model = 'config', $data = array(), $type = 1) 
	{
		$ids = input('ids');
		$status = input('status');
		$data['ids'] = $ids;
		$data['status'] = $status;
		return parent::setStatus($model, $data, $type);
	}
	/**
	 * @NodeAnotation(title="排序")
	 */
	public function sort($model = 'config', $data = array()) 
	{
		$data['sort'] = input('sort');
		return parent::sort($model, $data);
	}
	/**
     * @NodeAnotation(title="网站配置")
     */
	public function configuration() 
	{
		if (request()->isAjax()) {
			$data = input('post.');
			foreach ($data as $k => $v) {
				if(is_array($v)){
					if(array_level($v) == 2){ //数组字段值转为json数据
                        $arr = [];
                        foreach($v[0] as $k2=>$v2){
                            if($v2){
                                $arr[$v2] = $v[1][$k2];
                            }
                        }
                        $data[$k] = json_encode($arr);
                    }else{ //多选，把数组转为字符串以逗号隔开
                        $data[$k] = implode(',', $v);
                    }
                }else{
                    $data[$k] = $v;
				}
				if($k != 'is_record_operation_log'){
					$id = Db::name('config')->where('name',$k)->value('id');
					action_log($id, 'config', 2);
				}
				Db::name('config')->where('name' , $k)->update(['value' => $data[$k]]);
				if($k != 'is_record_operation_log'){
					action_log($id, 'config', 2);
				}
			}
			$this->success('更新成功！');
		}
		$id = input('id', 0);//获取选中配置类型id
		if (!$id) {
			$id = Db::name('config_type')
			->where('status' , 1)
			->order('sort desc,id desc')
			->limit(1)
			->value('id');
		}
		$configTypeRes = Db::name('config_type')
		->field('id,title')->where('status',1)
		->order('sort DESC')->select()->toArray();
		$title = Db::name('config_type')->where('id',$id)->value('title');
		$list = Db::name('config')
		->where([['typeid' ,'=', $id], ['status' ,'=', 1]])
		->order('sort desc,id asc')
		->select()
		->toArray();
		if ($title) {
			$meta_title = $title;
			if (!$list) {
				$list = [];
			}
		} else {
			$meta_title = '请设置好配置类型';
			$list = [];
		}
		// 扩展配置
        foreach($list as $key=>$value){
            $value['setting'] = unserialize($value['setting']);
            $value['options'] = $value['setting']['options']??'';
            if ($value['type'] == 'custom') {
				$value['custom'] = $value['setting']['custom']??'';
                if ($value['custom'] != '') {
                    $tpar             = explode(".", $value['custom'], 2);
                    $value['custom'] = $tpar[0];
                    unset($tpar);
                }else{
					$value['custom'] = 'custom';
				}
            } elseif ($value['options'] != '') {
                $value['options'] = parse_attr($value['options']);
            }
            $list[$key] = $value;
		}
		View::assign([
			'meta_title' => $meta_title,
			'id' => $id,//当前选中配置类型id
			'configTypeRes' => $configTypeRes,//所有配置类型信息
			'list' => $list,//当前选中的配置类型的所有配置
		]);
		return view();
	}
}
